<?php
/**
 * Created by PhpStorm.
 * User: P
 * Date: 2017/8/26
 * Time: 17:48
 */

namespace app\index\service;
use think\Config;
use think\Db;
use think\facade\Env;

class CasService
{
    public $cas_host = 'cer.ysu.edu.cn/authserver';
    public $cas_context = '';
    public $cas_port = 443;
    public $curbase,$curdir,$pgtBase,$cas_url;

    public function setConfig()
    {
        if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
            $curbase = 'https://' . $_SERVER['SERVER_NAME'];
        } else {
            $curbase = 'http://' . $_SERVER['SERVER_NAME'];
        }
        if ($_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
            $curbase .= ':' . $_SERVER['SERVER_PORT'];
        }
        $curdir = dirname($_SERVER['REQUEST_URI']) . "/";
        $pgtBase = preg_quote(preg_replace('/^http:/', 'https:', $curbase . $curdir), '/');
        $pgtUrlRegexp = '/^' . $pgtBase . '.*$/';
        $cas_url = 'https://' . $this->cas_host;
        if ($this->cas_port != '443') {
            $cas_url = $cas_url . ':' . $this->cas_port;
        }
        $cas_url = $cas_url . $this->cas_context;
        header('Content-Type: text/html; charset=utf-8');
    }

    public function initCas()
    {
        $this->setConfig();
        $config = new Config();
        $config->load(Env::get('extend_path').'CAS/CAS.php');
//        Config::load(EXTEND_PATH.'CAS/CAS.php');
        \phpCAS::client(CAS_VERSION_2_0,$this->cas_host,$this->cas_port,$this->cas_context,true);
        \phpCAS::setNoCasServerValidation();
    }

    public function getUserInfo()
    {
        $this->initCas();
        if(\phpCAS::checkAuthentication())
        {
            $attr = \phpCAS::getAttributes();
            $workno = \phpCAS::getUser();
            return array('userId'=>$workno, 'userPass'=>$attr);
        }
        else
        {
            // 访问CAS的验证
            \phpCAS::forceAuthentication();
        }
    }

    public function logout()
    {
        session(null);
        $this->initCAS();
        $param=array("service"=>url('index/Login/login','',true,false),
            "url"=>url('index/Login/login','',true,false));
        \phpCAS::logout($param);
    }

}